package protocol

import (
	"net"
)

type TCPPrvd struct {
	cli        net.Conn
	err        error

	cliIP     string

	// 统计信息
	sendBytes int64
	recvBytes int64
	sendPkgn  int64
	recvPkgn  int64
}


func (tcppvd *TCPPrvd) recv() (cmdid uint16, seqid uint16, msg string, err error) {

	bHeader := make([]byte, HEADLEN)
	for i := 0; i < HEADLEN; { // 接收报文头部
		nbyte, readErr := tcppvd.cli.Read(bHeader[i:])
		if nil != readErr {
			err = readErr
			return
		}
		i += nbyte
		tcppvd.recvBytes += int64(nbyte)
	}

	cmdid0, seqid0, bodyLen, parseErr := ParseHead(bHeader)
	if nil != parseErr {
		err = parseErr
		tcppvd.close()
		return
	}
	if bodyLen > MAXBODY_LEN {
		err = &MsgError{"bodyLen too large"}
		tcppvd.close()
		return
	}

	bodyMsg := make([]byte, bodyLen)
	for i := 0; i < int(bodyLen); { // 接收报文头部
		nbyte, readErr := tcppvd.cli.Read(bodyMsg[i:])
		if nil != readErr {
			err = readErr
			tcppvd.close()
			return
		}
		i += nbyte
		tcppvd.recvBytes += int64(nbyte)
	}

	tcppvd.recvPkgn += 1
	return cmdid0, seqid0, string(bodyMsg), nil
}